package fr.uvsq.isty.bdh.hchess.ranking;

import fr.uvsq.isty.bdh.hchess.util.GlobalConfig;
import java.io.*;
import java.util.ArrayList;

/**
 *
 * @author Clement Bellot <clementbellot@gmail.com>
 */
public class Players {
    private static Players instance = null;
    private String currentLoadedFile;
    private ArrayList<Player> players;
    
    public static Players getInstance() throws IOException {
        if(instance==null){
            instance = new Players();
	        String toLoad = GlobalConfig.getInstance().get("score", "playersfilepath", "data/players.db");
	        instance.Load(toLoad);
        }
        return instance;
    }
    
    private Players(){
    	players = new ArrayList<Player>();
    }
    
    public void Save() throws IOException {
        Save(currentLoadedFile);
    }
    
    public void Save(String fileName) throws IOException {
        ObjectOutputStream output =
                new ObjectOutputStream(new FileOutputStream(fileName));
        output.writeObject(players);
    }
    
    public void Load(String fileName) throws IOException {
    	ObjectInputStream input = null;
		File F = new File(fileName);
		F.createNewFile();
        try {
    	    input = new ObjectInputStream(new FileInputStream(fileName));
            players = (ArrayList<Player>) input.readObject();
            if(players==null){
            	Save(fileName);
            }
        } catch (ClassNotFoundException ex) {
        	Save(fileName);
        }catch(EOFException e){
        	Save(fileName);
        }
        if(input!=null){
        	input.close();
        }
        currentLoadedFile = fileName;
    }
    
    public ArrayList<Player> getItemsWithFilter(String prefix){
        ArrayList<Player> ret =new ArrayList<Player>();
        for(Player player : players){
            if(player.getName().startsWith(prefix)){
                ret.add(player);
            }
        }
        return ret;
    }
    
    public boolean addPlayer(Player p){
    	boolean alreadyExist = false;
    	for(Player curPlayer : players){
            if(curPlayer.getName().equals(p.getName())){
                    alreadyExist = true;
                    break;
            }
    	}
    	if(!alreadyExist){
    		players.add(p);
    	}
    	return alreadyExist;
    }
}
